import { createRouter, createWebHashHistory } from 'vue-router'
import { TOKEN } from '@/constant'
import { isEmptyObj } from '@/utils/validate'
import { usePermission } from '@st/modules/permission/hooks/usePermission'
import { useMenuStore } from '@/stores/menu'
import Layout from '@/layout/index.vue'

// 公开路由表
import publicRoutes, { whiteList } from './modules/public'
// 私有路由表
export const privateRoutes = []

const router = createRouter({
  history: createWebHashHistory(),
  routes: publicRoutes
})

privateRoutes.forEach((item) => {
  router.addRoute(item)
})

// 创建动态路由用
const modules = import.meta.glob('../views/**/*.vue')

// 创建动态路由
const buildAsyncRouters = (flatMenus: any[], routePath: string) => {
  let targetRouteName = null
  flatMenus.forEach((item: any) => {
    const tmp = {
      path: `/${item.path}`,
      name: item.name,
      component: Layout,
      children: [] as any[]
    }
    item.children.forEach((ele: any) => {
      tmp.children.push({
        path: ele.path,
        name: `${item.name}-${ele.path}`,
        meta: ele.meta,
        component: modules[`../views/${ele.component}.vue`]
      })
      if (routePath) {
        if (routePath === `/${item.path}/${ele.path}`) {
          targetRouteName = `${item.name}-${ele.path}`
        }
      }
    })
    router.addRoute(tmp)
  })
  return targetRouteName
}

// 系统标签检测标记
let checkedSysTagFlg = false

// 全局路由守卫
router.beforeEach((to, form, next) => {
  const token = localStorage.getItem(TOKEN)
  if (isEmptyObj(token)) {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  } else {
    // 给页面上各种组件加载一个缓冲
    const menuStore = useMenuStore()
    menuStore.setChanging(true)
    // ====== 权限集成 ======
    const permissionFlg = import.meta.env.VITE_APP_PLUGINS.includes('permission')
    if (permissionFlg) {
      const { getFlatMenus, getFirst, checkSysTag } = usePermission()
      // 判断系统标签是否正确
      if (!checkedSysTagFlg) {
        checkedSysTagFlg = true
        if (!checkSysTag()) {
          return
        }
      }
      // 权限跳转处理
      if (whiteList.indexOf(to.path) > -1) {
        next()
      } else {
        if (!to.name || !router.hasRoute(to.name)) {
          const targetRouteName = buildAsyncRouters(getFlatMenus(), to.path)
          if (!targetRouteName) {
            // 不存在
            next('/not-auth')
          } else {
            next({
              ...to,
              replace: true
            })
          }
        } else {
          if (to.path === '/') {
            next(getFirst())
          } else {
            next()
          }
        }
      }
    }
    // ====== 权限集成 ======
    if (!permissionFlg) {
      next()
    }
  }
})

export default router
